package com.primary.controller;

import com.primary.common.Result;
import com.primary.controller.dto.DbInfoDto;
import com.primary.controller.dto.SystemInfosDto;
import com.sun.management.OperatingSystemMXBean;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.lang.management.ManagementFactory;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;

/**
 * @author Shen Jianhui
 * @date 2024/03/02 23:11 Saturday
 * @description
 */
@RestController
@RequestMapping("/system")
public class SystemInfoController {

    @RequestMapping(value = "/info", method = {RequestMethod.GET})
    public Result getSystem() throws UnknownHostException, InterruptedException {
        InetAddress localhost = InetAddress.getLocalHost();
        SystemInfosDto systemInfosDto = new SystemInfosDto();
        systemInfosDto.setIpAddress(localhost.getHostAddress());
        systemInfosDto.setHostName(localhost.getHostName());
        Properties props = System.getProperties();
        systemInfosDto.setOsName(props.getProperty("os.name"));
        systemInfosDto.setOsVersion(props.getProperty("os.version"));
        OperatingSystemMXBean operatingSystemMXBean = (OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean();
        systemInfosDto.setTotalPhysicalMemorySize(operatingSystemMXBean.getTotalMemorySize() / (1024 * 1024)+" MB");
        systemInfosDto.setAvailableProcessors(operatingSystemMXBean.getAvailableProcessors());
        systemInfosDto.setSystemCpuLoad(String.format("%.2f%%", operatingSystemMXBean.getCpuLoad() *100));
        Thread.sleep(1000);
        return Result.success(systemInfosDto);
    }
    @RequestMapping(value = "dbinfo",method = {RequestMethod.GET})
    public Result getDbinfo() throws ClassNotFoundException, SQLException {
        SystemInfosDto systemInfosDto = new SystemInfosDto();
        String URL= DbInfoDto.dbURL;
        String DRIVER= DbInfoDto.driver;
        String USERNAME= DbInfoDto.dbUsername;
        String PASSWORD= DbInfoDto.dbPassword;
        Class.forName(DRIVER);
        Connection con = DriverManager.getConnection(URL,USERNAME,PASSWORD);
        DatabaseMetaData metaData = con.getMetaData();
        systemInfosDto.setDatabaseProductInfo(metaData.getDatabaseProductName());
        systemInfosDto.setDatabaseVersion(metaData.getDatabaseProductVersion());
        return Result.success(systemInfosDto);
    }
}
